using System;
using MQTTnet.Diagnostics;

namespace HslCommunicationEx.Mqtt
{
	public class MqttNetLogger : IMqttNetLogger
	{
		private readonly object _consoleSyncRoot = new object();

		public Action<MqttNetLogLevel, string> ConsoleLogHandler { get; set; }

		public bool IsEnabled => true;

		public void Publish(MqttNetLogLevel logLevel, string source, string message, object[] parameters, Exception exception)
		{
			ConsoleColor consoleColor = ConsoleColor.White;
			switch (logLevel)
			{
			case MqttNetLogLevel.Verbose:
				consoleColor = ConsoleColor.White;
				break;
			case MqttNetLogLevel.Info:
				consoleColor = ConsoleColor.Green;
				break;
			case MqttNetLogLevel.Warning:
				consoleColor = ConsoleColor.DarkYellow;
				break;
			case MqttNetLogLevel.Error:
				consoleColor = ConsoleColor.Red;
				break;
			}
			if (parameters != null && parameters.Length != 0)
			{
				message = string.Format(message, parameters);
			}
			lock (this._consoleSyncRoot)
			{
				this.ConsoleLogHandler?.Invoke(logLevel, message);
			}
		}
	}
}
